package com.centaline.androidsalesblog.activities.newest;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.IBinder;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseIntArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.adapter.ImgListBrowseAdapter;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.model.businissobject.NewPropImgBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centanet.framework.base.BaseAdapter1;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.service.ImageDownloadService;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.ArrayList;
import java.util.Locale;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 新房图册
 * Created by guilin on 16/2/25.
 */
public class NewPropImgListActivity extends BaseActivity {

    private ViewPager viewPager;
    private RecyclerView rv_img_type;

    private ImgListBrowseAdapter imgListBrowseAdapter;
    private TitleAdapter titleAdapter;
    private ArrayList<String> imgList = new ArrayList<>();//显示图片合集
    private ArrayList<String> imgListThumbnail = new ArrayList<>();//缩略图片合集
    private ArrayList<NewPropImgBo> newPropImgBos = new ArrayList<>();//新房图片合集
    private ArrayList<String> titleList = new ArrayList<>();//新房图片类型标题合集
    private SparseIntArray sparseIntArray = new SparseIntArray();//图片类型末端位置
    private int pageViewPos;//当前位置
    private int titlePos;//类型标题位置
    private String newPropImg;

    private ImageDownloadService.DownloadBinder downloadBinder;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (ImageDownloadService.DownloadBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected int setLayoutId() {
        return R.layout.activity_new_prop_img_list;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar();
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        rv_img_type = (RecyclerView) findViewById(R.id.rv_img_type);
    }

    @Override
    protected void initViews() {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                pageSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        imgListBrowseAdapter = new ImgListBrowseAdapter(viewPager, GlideLoad.init(this), imgList, imgListThumbnail);
        viewPager.setAdapter(imgListBrowseAdapter);
        rv_img_type.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
//        rv_img_type.addItemDecoration(new TiTleDecoration());
        titleAdapter = new TitleAdapter(this);
        rv_img_type.setAdapter(titleAdapter);

        final ArrayList<NewPropImgBo> temp = getIntent().getParcelableArrayListExtra(ExtraConstant.NewPropImgList);
        newPropImgBos.addAll(temp);
        pageViewPos = getIntent().getIntExtra(ExtraConstant.IMG_POS, 0);
        bizUnit();
    }

    /**
     * 初始化数据
     */
    private void initData() {
        for (NewPropImgBo newPropImgBo : newPropImgBos) {
            final String imgType = newPropImgBo.getImgType();
            String imgAddress = newPropImgBo.getFileUrl();
            String imgAddressThumb = newPropImgBo.getFileUrl();
            imgAddress = imgAddress == null || !imgAddress.contains(".") ? "" :
                    String.format(Locale.CHINA,
                            "%s%s",
                            newPropImg,
                            imgAddress.replace(".",
                                    String.format(Locale.CHINA, "_%dx%d_f.", newPropImgBo.getWidth(), newPropImgBo.getHeight())));
            imgAddressThumb = imgAddressThumb == null || !imgAddressThumb.contains(".") ? "" :
                    String.format(Locale.CHINA,
                            "%s%s",
                            newPropImg,
                            imgAddressThumb.replace(".",
                                    String.format(Locale.CHINA, "_%dx%d_f.", newPropImgBo.getWidth() * 10 / 100, newPropImgBo.getHeight() * 10 / 100)));
            imgListThumbnail.add(imgAddressThumb);
            imgList.add(imgAddress);
            if (!titleList.contains(imgType)) {
                titleList.add(imgType);
            }
            sparseIntArray.put(titleList.size() - 1, imgList.size());
        }
        imgListBrowseAdapter.notifyDataSetChanged();
        viewPager.setCurrentItem(pageViewPos, true);
        bindService(new Intent(this, ImageDownloadService.class), serviceConnection, BIND_AUTO_CREATE);
        if (pageViewPos == 0) {
            pageSelected(0);
        }
    }

    /**
     * 选择位置
     */
    private void pageSelected(int position) {
        final String imgType = newPropImgBos.get(position).getImgType();
        final int index = titleList.indexOf(imgType);
        if (titlePos != index) {
            titlePos = index;
            titleAdapter.setSelectPost(titlePos);
            rv_img_type.smoothScrollToPosition(titlePos);
        }
        if (index > 0) {
            setToolbarTitle(String.format(Locale.CHINA, "%d/%d",
                    (position + 1 - sparseIntArray.get(index - 1)),
                    (sparseIntArray.get(index) - sparseIntArray.get(index - 1))));
        } else {
            setToolbarTitle(String.format(Locale.CHINA, "%d/%d",
                    (position + 1), sparseIntArray.get(0)));
        }
        pageViewPos = position;
    }

    @Override
    protected void onDestroy() {
        unbindService(serviceConnection);
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (imgList.size() > 0)
            getMenuInflater().inflate(R.menu.menu_download, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_download) {
            downloadBinder.startDownload(imgList.get(pageViewPos));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 获取配置信息
     */
    private void bizUnit() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        newPropImg = bizUnitDo.getNewpropimg();
                        initData();
                    }
                });
    }

    /**
     * 图片类型标题
     */
    class TitleAdapter extends BaseAdapter1<TitleVH> {

        private int selectPost;

        public TitleAdapter(Context context) {
            super(context);
        }

        public void setSelectPost(int selectPost) {
            this.selectPost = selectPost;
            notifyDataSetChanged();
        }

        @Override
        protected int inflateByLayoutId() {
            return R.layout.item_new_prop_img_title;
        }

        @Override
        protected TitleVH viewHolder(View view) {
            return new TitleVH(view);
        }

        @Override
        public void onBindViewHolder(final TitleVH holder, int position) {
            final boolean isCurrent = selectPost == position;
            holder.atv_title.setText(titleList.get(position));
            holder.atv_title.setTextColor(isCurrent ?
                    Color.parseColor("#FD4607") : Color.parseColor("#FFFFFF"));
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!isCurrent) {
                        viewPager.setCurrentItem(holder.getAdapterPosition() > 0 ?
                                sparseIntArray.get(holder.getAdapterPosition() - 1) : 0, true);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return titleList.size();
        }
    }


    class TitleVH extends RecyclerView.ViewHolder {

        public AppCompatTextView atv_title;

        public TitleVH(View itemView) {
            super(itemView);
            atv_title = (AppCompatTextView) itemView.findViewById(R.id.atv_title);
        }
    }

    /**
     * 分割线
     */
//    class TiTleDecoration extends RecyclerView.ItemDecoration {
//
//        private Drawable mDivider;
//
//        public TiTleDecoration() {
//            mDivider = getDrawable(R.drawable.ic_new_prop_img_divider);
//        }
//
//        @Override
//        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
//            super.onDraw(c, parent, state);
//            final int top = 30;
//            final int bottom = parent.getHeight() - 10;
//            final int childCount = parent.getChildCount();
//            for (int i = 0; i < childCount; i++) {
//                final View child = parent.getChildAt(i);
//                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
//                        .getLayoutParams();
//                final int left = child.getRight() + params.rightMargin +
//                        Math.round(ViewCompat.getTranslationX(child));
//                final int right = left + 2;
//                mDivider.setBounds(left, top, right, bottom);
//                mDivider.draw(c);
//            }
//        }
//    }
}
